package com.codingapi.p2p.client.service.impl;

import com.codingapi.p2p.client.handler.NettyClientHandler;
import com.codingapi.p2p.client.service.NettyClientService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * create by lorne on 2018/3/13
 */

public class NettyClientServiceImpl implements NettyClientService {


    private EventLoopGroup group;

    private Logger logger = LoggerFactory.getLogger(NettyClientServiceImpl.class);

    private String host;
    private int port;

    public NettyClientServiceImpl(String host, int port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public void start() {
        group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_REUSEADDR,true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();

                            p.addLast(new NettyClientHandler());
                        }
                    });

            // Make the connection attempt.
//            b.bind(new InetSocketAddress(host, port));
            b.connect(new InetSocketAddress(host, port));

            logger.info("netty client - listener ! ");

        }catch (Exception e){
            close();
        }
    }

    @Override
    public void close() {
        group.shutdownGracefully();

        logger.info("netty- close ! ");
    }

}
